<template>
  <div
    class=""
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <el-row>
      <el-col :span="24">
        <aps-form
          :config="apsForm.formConfig"
          :model="apsForm.formData"
          :formRef="apsForm.formRef"
          :labelWidth="apsForm.labelWidth"
          ref="form"
        ></aps-form>
      </el-col>
    </el-row>
    <!-- <circuitBarchart :chartData="chartData" style="margin-bottom: 20px" /> -->
    <lb-table
      ref="table"
      :column="tableData.column"
      :data="tableData.data"
      height="600"
      pagination
      background
      border
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 40]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
  </div>
</template>

<script>
import circuitBarchart from "@/views/statistics/energy/components/behaviorC/circuitBarchart.vue";
import CascaderSelect from "@/components/Select/CascaderSelect";
import RemoteSelect from "@/components/Select/RemoteSelect";
import { getGraphChart, getGraphForm } from "@/api/iot/circuit.js";
import { dealElectricity, deepClone } from "@/utils/index";
export default {
  components: {
    circuitBarchart,
    CascaderSelect,
    RemoteSelect,
  },
  dicts: ["subentry_type"],
  data() {
    return {
      sysDeptId: [],
      netwoekChose: null,
      extraParams: {},
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            startAndend: {
              label: "日期范围:",
              typeName: "el-date-picker",
              type: "daterange",
              size: "small",
              "start-placeholder": "请选择开始日期",
              "end-placeholder": "请选择结束日期",
              "picker-options": {
                disabledDate: (time) => {
                  // 禁用今天之后的日期【当前天可选】
                  return time.getTime() >= Date.now();
                },
              },
              "value-format": "yyyy-MM-dd HH:mm:ss",
            },
            sysDeptId: {
              label: "用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().sysDeptId;
                return (
                  <div>
                    <CascaderSelect
                      value={valNum}
                      values={valNum}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择用能单位"}
                      filterable={true}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            monitoringNetworkId: {
              label: "能耗终端:",
              typeName: "el-select",
              render: () => {
                let that = this;
                return (
                  <div>
                    <RemoteSelect
                      v-model={that.netwoekChose}
                      varient="networks"
                      extraParams={that.extraParams}
                      placeholder={"请选择能耗终端"}
                      size={"small"}
                      onInput={that.choseNetwork}
                    ></RemoteSelect>
                  </div>
                );
              },
            },
            cardNum: {
              label: "物联网卡号:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入物联网卡号",
            },
            deviceCode: {
              label: "设备编号:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入设备编号",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
          ],
        },
      },
      chartData: {
        legendData: ["总能耗", "支路总能耗"],
        color: ["#5C9CD5", "#10B767", "#ED7D31", "#A5A5A5", "#FFC000"],
        xAxisData: [],
        seriesData: [
          {
            name: "总能耗",
            type: "line",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
          {
            name: "支路总能耗",
            type: "line",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
        ],
      },
      tableData: {
        column: [
          {
            prop: "deptName",
            label: "用能单位",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "monitoringName",
            label: "能耗终端",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceCode",
            label: "设备编号",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "cardNum",
            label: "物联网卡号",
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "summaryEnergyConsumption",
            label: "主表能耗(kwh)",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let num = dealElectricity(
                scope.row?.summaryEnergyConsumption ?? 0
              );
              return h("div", num);
            },
          },
          {
            prop: "branchEnergyConsumption",
            label: "支路能耗(kwh)",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let num = dealElectricity(
                scope.row?.branchEnergyConsumption ?? 0
              );
              return h("div", num);
            },
          },
          {
            prop: "differenceValue",
            label: "差值(kwh)",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let num = dealElectricity(scope.row?.differenceValue ?? 0);
              return h("div", num);
            },
          },
          {
            prop: "differencePercentage",
            label: "差值百分比(%)",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let num = dealElectricity(
                scope.row?.differencePercentage ?? 0,
                1,
                2
              );
              return h("div", num);
            },
          },
          {
            prop: "dateStr",
            label: "统计时间",
            align: "center",
            showOverflowTooltip: true,
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      queryParams: {},
    };
  },
  created() {},
  mounted() {
    this.handlerSearchDetail();
  },
  methods: {
    handlerSearchDetail() {
      const { startAndend, ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
        monitoringNetworkId: this.netwoekChose,
      };
      if (startAndend) {
        data.startTime = startAndend[0];
        data.endTime = startAndend[1];
      }
      this.queryParams = data;
      this.getTablelist(this.queryParams);
      // this.getchartData(this.queryParams);
    },
    // 获取列表数据
    getTablelist(data) {
      let params = { ...data };
      params.pageSize = this.pageSize;
      params.pageNum = this.currentPage;
      this.$store.commit("app/updateApiCount", "add");
      getGraphForm(params)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.tableData.data = res?.rows ?? [];
          this.total = res?.total ?? 0;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!200901");
        });
    },
    // 获取图表数据
    getchartData(data) {
      let params = { ...data };
      getGraphChart(params)
        .then((res) => {
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          this.chartDataReset();
          if (arr.length > 0) {
            this.graphChartDatadeal(deepClone(arr));
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200900");
        });
    },
    // 重置图表
    chartDataReset() {
      this.chartData = {
        legendData: ["总能耗", "支路总能耗"],
        color: ["#5C9CD5", "#10B767", "#ED7D31", "#A5A5A5", "#FFC000"],
        xAxisData: [],
        seriesData: [
          {
            name: "总能耗",
            type: "line",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
          {
            name: "支路总能耗",
            type: "line",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          },
        ],
      };
    },
    graphChartDatadeal(arr) {
      let typeArr = this.dict?.type?.subentry_type ?? [];
      let subentryTypeArr = [];
      let nameArr = [];
      arr.map((item) => {
        // 柱状图每条总能耗
        this.chartData.seriesData[0].data.push(
          dealElectricity(item?.summaryEnergyConsumption ?? 0, 100, 2)
        );
        // 柱状图每条支路总能耗
        this.chartData.seriesData[1].data.push(
          dealElectricity(item?.branchEnergyConsumption ?? 0, 100, 2)
        );
        // 柱状图X轴
        this.chartData.xAxisData.push(item?.dateTime ?? "");
        // bar数据整理
        let slist = item?.subentryTypeConsumptionBOList ?? [];
        if (slist.length > 0) {
          slist.map((pig) => {
            typeArr.map((tig) => {
              if (pig.subentryType == tig.value) {
                pig.name = tig.label;
              }
            });
            if (subentryTypeArr.length == 0) {
              subentryTypeArr.push(pig.subentryType);
              nameArr.push(pig.name);
            } else {
              if (subentryTypeArr.indexOf(pig.subentryType) == -1) {
                subentryTypeArr.push(pig.subentryType);
                nameArr.push(pig.name);
              }
            }
          });
        }
      });
      // console.log(arr, subentryTypeArr, nameArr);
      // 添加bar
      if (subentryTypeArr.length > 0) {
        subentryTypeArr.map((sig, sigindex) => {
          this.chartData.legendData.push(nameArr[sigindex]);
          let obj = {
            name: nameArr[sigindex],
            subentryType: sig,
            type: "bar",
            stack: "add",
            tooltip: {
              valueFormatter: function (value) {
                return value + " kwh";
              },
            },
            data: [],
          };
          this.chartData.seriesData.push(obj);
        });
      }
      // bar 的data数据传入
      arr.map((item) => {
        let slist2 = item?.subentryTypeConsumptionBOList ?? [];
        let slist2Length = slist2.length;
        this.chartData.seriesData.map((mig) => {
          mig.hasValue = false;
          let num = 0;
          if (slist2Length > 0) {
            slist2.map((tig) => {
              if (mig.subentryType == tig.subentryType) {
                mig.data.push(
                  dealElectricity(tig?.energyConsumption ?? 0, 100, 2)
                );
                mig.hasValue = true;
              } else {
                num++;
              }
            });
            if (num == slist2Length) {
              if (!mig.hasValue) {
                mig.data.push(dealElectricity(0, 100, 2));
                mig.hasValue = true;
              }
            }
          } else {
            if (!mig.hasValue) {
              mig.data.push(dealElectricity(0, 100, 2));
              mig.hasValue = true;
            }
          }
        });
      });
      // console.log(this.chartData, "chartData");
    },
    handleReset() {
      this.$refs?.form?.resetFields();
      this.queryParams = {};
      this.sysDeptId = [];
      this.netwoekChose = null;
      this.extraParams = {};
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handlerLiandong(value) {
      this.netwoekChose = null;
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
      // 请求能耗终端
      this.extraParams = {
        sysDeptId: result,
      };
    },
    /* 选择能耗终端 */
    choseNetwork(value) {
      this.netwoekChose = value;
    },
  },
};
</script>

<style lang="scss" scoped></style>
